import os
import time
import uuid
import re
from functools import reduce

import cv2
import numpy as np
from datetime import timedelta
from flask import Flask, render_template, request, jsonify
from paddleocr import PaddleOCR
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(hours=1)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
app.config['CACHES_FOLDER'] = 'D:/workbench/ocr cache/'


def allowed_file(fname):
    return '.' in fname and fname.rsplit('.', 1)[1].lower() in ['png', 'jpg', 'jpeg']


@app.route("/file")
def upfile():
    return render_template('file.html')


@app.route('/ocr', methods=['POST', 'GET'])
def detect():
    file = request.files['file']
    if file and allowed_file(file.filename):
        ext = file.filename.rsplit('.', 1)[1]
        random_name = '{}.{}'.format(uuid.uuid4().hex, ext)
        save_path = os.path.join(app.config['CACHES_FOLDER'], secure_filename(random_name))
        file.save(save_path)
        # time-1
        time.sleep(0.1)
        t1 = time.time()
        img = cv2.imread(save_path)
        img_result = ocr.ocr(img, cls=False, det=False, rec=True)
        p = re.compile(r'[(](.*?)[)]', re.S)
        res = re.findall(p, img_result[0][0][0])
        print(res)
        r = re.split(",|\\.", res[0])
        print(r)
        x = r[0]
        y = r[1]

        # time-2
        t2 = time.time()
        return jsonify({
            'code': 'success',
            'x': x,
            'y': y,
            '识别时间': '{:.4f}s'.format(t2 - t1)
        })
    return jsonify({'code': 'failed'})


@app.route('/ocrAll', methods=['POST', 'GET'])
def ocrAll():
    file = request.files['file']
    if file and allowed_file(file.filename):
        ext = file.filename.rsplit('.', 1)[1]
        random_name = '{}.{}'.format(uuid.uuid4().hex, ext)
        save_path = os.path.join(app.config['CACHES_FOLDER'], secure_filename(random_name))
        file.save(save_path)
        # time-1
        t1 = time.time()
        img = cv2.imread(save_path)
        img_result = ocr.ocr(img, cls=True, det=True, rec=True)
        print(time.time() - t1)
        res = []
        for item in img_result[0]:
            x = 0.0
            y = 0.0
            for it in item[0]:
                x += it[0]
                y += it[1]
            if item[1][1] > 0.8:
                res.append({'x': x / 4, 'y': y / 4, 'text': item[1][0]})
        print(res)
        return jsonify({'code': 200, 'data': res})
    return jsonify({'code': 0})


if __name__ == '__main__':
    ocr = PaddleOCR(use_gpu=True)  # 查看README的参数说明
    app.run(host='192.168.10.24', port=8090, debug=True, threaded=True, processes=1)
